package com.wwtech.epp.ui.activity.main;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import com.lzy.widget.AlphaIndicator;
import com.ninjia.ninjiabaselibrary.utils.SpUtil;
import com.socks.library.KLog;
import com.wwtech.epp.R;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.base.BaseActivity;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.entity.UserLogin;
import com.wwtech.epp.entity.eventbus.UnreandChange;
import com.wwtech.epp.ui.activity.login.SplashActivity;
import com.wwtech.epp.ui.activity.main.component.DaggerMainComponent;
import com.wwtech.epp.ui.activity.main.contract.MainContract;
import com.wwtech.epp.ui.activity.main.module.MainModule;
import com.wwtech.epp.ui.activity.main.presenter.MainPresenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.main
 * @Description: $description
 * @date 2017/08/02 08:43:44
 */

public class MainActivity extends BaseActivity implements MainContract.View, IUnReadMessageObserver {

    @Inject
    MainPresenter mPresenter;
    @BindView(R.id.id_viewPager)
    ViewPager idViewPager;
    @BindView(R.id.alphaIndicator)
    AlphaIndicator alphaIndicator;
    @BindView(R.id.unread_count)
    TextView unreadCount;
    /**
     * 会话列表的fragment
     */
    private ConversationListFragment mConversationListFragment = null;
    private boolean isDebug;
    private Context mContext;
    private Conversation.ConversationType[] mConversationsTypes = null;

    private List<String> mTitles = Arrays.asList("消息", "通讯录", "工作", "我的");
    private List<Fragment> mFragments = new ArrayList<>();
    private FragmentPagerAdapter mPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        KLog.i("开始保存");
        outState.putParcelable("login", ContainValue.userLogin.getData());
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        ContainValue.userLogin = new UserLogin();
        KLog.i("开始恢复");
        ContainValue.userLogin.setData(savedInstanceState.getParcelable("login"));
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_main);
        toolbar.setVisibility(View.GONE);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        for (String title : mTitles) {
            if (title.equals("消息")) {
//                mFragments.add(initConversationList());
                mFragments.add(new InformFragment());
            } else if (title.equals("通讯录")) {
                mFragments.add(new ContactFragment());
            } else if (title.equals("工作")) {
                mFragments.add(new WorkFragment());
            } else {
                mFragments.add(new MyFragment());
            }
        }

        mPagerAdapter = new TopViewPagerAdapter(getSupportFragmentManager(), this, mFragments);
        idViewPager.setOffscreenPageLimit(3);
        idViewPager.setAdapter(mPagerAdapter);
        alphaIndicator.setViewPager(idViewPager);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUnreadMessageChange(UnreandChange unreandChange) {
        RongIMClient.getInstance().getTotalUnreadCount(new RongIMClient.ResultCallback<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                KLog.i(integer + "未读消息数");
                unreadCount.setText(integer + "");
                if(integer == 0) {
                    unreadCount.setVisibility(View.GONE);
                } else {
                    unreadCount.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initData() {
        mPresenter.doGetToken();
//        connect(SpUtil.getString(this, ContainValue.LOGINTOKEN, ""));
        KLog.i("token为：" + SpUtil.getString(this, ContainValue.LOGINTOKEN, ""));
        AppConfig.getInstance().openSealDBIfHasCachedToken();
        KLog.i("用户id为：" + ContainValue.userLogin.getData().getUserId());
//        SharedPreferences preferences = getSharedPreferences("RongKitConfig", 0);
//        SharedPreferences.Editor editor = preferences.edit();
//        editor.putString("userID", ContainValue.userLogin.getData().getUserId() + "");
//        editor.commit();
        RongIM.getInstance().setCurrentUserInfo(new UserInfo(ContainValue.userLogin.getData().getUserId() + "", ContainValue.userLogin.getData().getNickName(), Uri.parse(ContainValue.userLogin.getData().getAvatar())));
        RongIM.getInstance().setMessageAttachedUserInfo(true);
        final Conversation.ConversationType[] conversationTypes = {
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP, Conversation.ConversationType.SYSTEM,
                Conversation.ConversationType.PUBLIC_SERVICE, Conversation.ConversationType.APP_PUBLIC_SERVICE
        };

        RongIM.getInstance().addUnReadMessageCountChangedObserver(this, conversationTypes);

    }

    @Override
    protected void setupActivityComponent() {
        DaggerMainComponent
                .builder()
                .appComponent(((AppConfig) getApplication()).getApplicationComponent())
                .mainModule(new MainModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setPresenter(MainContract.MainContractPresenter presenter) {
        mPresenter = (MainPresenter) presenter;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

    @Override
    public void setToekn(String content) {
        connect(content);
        SpUtil.putString(this, "loginToken", content);
    }

    @Override
    public void getTokenFailed() {
        startActivity(new Intent(this, SplashActivity.class));
        finish();
    }

    @Override
    public void onCountChanged(int i) {
        unreadCount.setText(i + "");
        if(i == 0) {
            unreadCount.setVisibility(View.GONE);
        } else {
            unreadCount.setVisibility(View.VISIBLE);
        }
    }

    public class TopViewPagerAdapter extends FragmentPagerAdapter {
        private Context mContext;
        private List<Fragment> mFragments;

        public TopViewPagerAdapter(FragmentManager fm, Context context, List<Fragment> fragments) {
            super(fm);
            mContext = context;
            mFragments = fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }
    }

    /**
     * <p>连接服务器，在整个应用程序全局，只需要调用一次，需在 {@link //init(Context)} 之后调用。</p>
     * <p>如果调用此接口遇到连接失败，SDK 会自动启动重连机制进行最多10次重连，分别是1, 2, 4, 8, 16, 32, 64, 128, 256, 512秒后。
     * 在这之后如果仍没有连接成功，还会在当检测到设备网络状态变化时再次进行重连。</p>
     *
     * @param token 从服务端获取的用户身份令牌（Token）。
     * @return RongIM  客户端核心类的实例。
     */
    private void connect(String token) {
        if (getApplicationInfo().packageName.equals(AppConfig.getCurProcessName(getApplicationContext()))) {
            KLog.i("开始连接融云");
            RongIM.connect(token, new RongIMClient.ConnectCallback() {

                /**
                 * Token 错误。可以从下面两点检查 1.  Token 是否过期，如果过期您需要向 App Server 重新请求一个新的 Token
                 *                  2.  token 对应的 appKey 和工程里设置的 appKey 是否一致
                 */
                @Override
                public void onTokenIncorrect() {
                    KLog.i("额？？？");
                }

                /**
                 * 连接融云成功
                 * @param userid 当前 token 对应的用户 id
                 */
                @Override
                public void onSuccess(String userid) {
//                    ToastUtil.showShort("设置token成功");
//                    Log.d("LoginActivity", "--onSuccess" + userid);
//                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
//                    finish();
//                    onUnreadMessageChange(new UnreandChange());
                }

                /**
                 * 连接融云失败
                 * @param errorCode 错误码，可到官网 查看错误码对应的注释
                 */
                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    KLog.i("连接融云失败");
                    KLog.i(errorCode);
                }
            });
        } else {
            KLog.i("错误。。。。。。。。。。。");
        }
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }
}